class User < ActiveRecord::Base
  attr_protected            :password_salt, :password_hash, :is_teacher, :is_admin
  attr_accessor             :password
  
  # Relations
  has_many                  :uploads
  has_many                  :teachings,
                            :dependent => :destroy
  has_and_belongs_to_many   :groups
  
  # Validators
  validates_presence_of     :name, :email, :password_salt, :password_hash
  validates_uniqueness_of   :email
  validates_confirmation_of :password
  validates_format_of       :email,
                            :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
  # Creates accessor method to assign a new password.
  # Creates a new salt then hashes the password
  #
  def password=(pass)
    @password = pass
    unless pass.nil? || pass.blank?
      salt = [Array.new(6){rand(256).chr}.join].pack('m').chomp
      self.password_salt, self.password_hash = salt, User.hash_password(pass, salt)
    end
  end
  
  # Tries to login email using pass
  #
  def self.authenticate(email, pass)
    user = User.find(:first, :conditions => {:email => email})
    return ((user && (user.password_hash == User.hash_password(pass, user.password_salt))) ? user : nil)
  end
  
  # Hashes pass using salt
  #
  def self.hash_password(pass, salt)
    Digest::SHA256.hexdigest(pass + salt)
  end
  
  # Returns a random password
  #
  def self.get_random_password
    Digest::SHA256.hexdigest(rand(150).to_s + Time.now.to_s)[0,10]
  end
end